/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.dao.hibernate;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ibm.iisp.common.vo.AuditVO;

/**
 * 类作用：
 * @author Johnny@cn.ibm.com
 * 使用说明：
 * <!--<prop key="hibernate.ejb.interceptor">com.ibm.iisp.common.dao.hibernate.AuditInterceptor</prop>-->
 */
public class AuditInterceptor extends EmptyInterceptor{
	/**
	 * 
	 */
	private static final long serialVersionUID = -8625914405583497231L;
	private Logger log = LoggerFactory.getLogger(getClass());
			
	/* (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onSave(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
	 */
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		if (entity instanceof AuditVO) {
			String username = SecurityContextHolder.getContext().getAuthentication().getName();
			log.trace("audit vo tercepted {}, {}", entity, username);
			AuditVO vo = (AuditVO)entity;
			vo.setLastUpdateUser(username);
			if (vo.getCreateUser() == null) {
				vo.setCreateUser(username);
				vo.setCreateTime(new Date());
			}
		}
		return super.onSave(entity, id, state, propertyNames, types);
	}
	
}
